package com.fly.web.controller;

import java.util.concurrent.TimeUnit;

import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
@Api(tags = "测试WebClient2")
@RestController
public class WebClient2Controller
{
    @GetMapping("/data")
    public Student getDefaultDate()
        throws InterruptedException
    {
        TimeUnit.MILLISECONDS.sleep(1000L);
        return new Student().setDesc("nice");
    }
    
    @ApiOperation("test1")
    @GetMapping("/test1")
    public String test1()
    {
        // 方式一，直接调用create()方法, retrieve 获取响应体
        WebClient webClient = WebClient.create();
        Mono<String> mono = webClient.get().uri("http://localhost:8080/data").retrieve().bodyToMono(String.class);
        return "from test1 " + mono.block();
    }
    
    @ApiOperation("test2")
    @GetMapping("/test2")
    public Student test2()
    {
        // 方式二，调用builder()方法进行创建，可以自定义标头，基础链接
        WebClient webClient =
            WebClient.builder().baseUrl("http://localhost:8080").defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)").defaultCookie("ACCESS_TOKEN", "test_token").build();
        Mono<Student> mono = webClient.get().uri("/data").retrieve().bodyToMono(Student.class);
        Student student = mono.block();
        student.setDesc("From test2");
        return student;
    }
    
    @ApiOperation("test3")
    @GetMapping("/test3")
    public String test3()
    {
        // 支持异步调用的方式
        WebClient webClient =
            WebClient.builder().baseUrl("http://localhost:8080").defaultHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)").defaultCookie("ACCESS_TOKEN", "test_token").build();
        Mono<Student> mono = webClient.get().uri("/data").retrieve().bodyToMono(Student.class);
        mono.subscribe(value -> log.info("{}", value));
        return "正在进行网路请求。。。";
    }
}

@Data
@Accessors(chain = true)
class Student
{
    String desc;
}